/**
 * 
 */
package info.niwota.web.jetty;

import info.niwota.web.Debug;
import info.niwota.web.Session;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import android.content.Context;
import android.util.Log;

/**
 * @author qiangli
 *
 */
public class HttpHandler extends BaseHandler {

	private static final String TAG = "HttpHandler";

	private BaseHandler defaultHandler;

	/**
	 * @param ctx
	 */
	public HttpHandler(Context ctx) {
		super(ctx);
		//
		init();
	}


	private void init() {
		defaultHandler = new DefaultHandler(ctx);
	}
	
	@Override
	public boolean handle(String p, HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			if (!dispatch(p, request, response)) {
				// TODO default
				response.setContentType("text/html");
				response.setStatus(HttpServletResponse.SC_OK);
				response.getWriter().println("Page not found: " + p);
			}
		} catch (Exception e) {
			if (Debug.DEBUG) {
				e.printStackTrace();
			}
			sendError(p, request, response, e);
		}
		return true;
	}
	
	private boolean dispatch(String p, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// handle system path
		if (p != null) {
			// help
			// settings
			// logout
			if (p.startsWith("/bin/logout")) {
				Session s = (Session) request.getAttribute("session");
				if (s != null) {
					String sid = s.id;
					if (Debug.DEBUG) {
						Log.d(TAG, "dispatch logout  sid: " + sid);
					}
					sessions.remove(sid);
					s.authenticated = false;
				}
				redirectHome(request, response);
				return true;
			}
		}
		
		if (defaultHandler.handle(p, request, response)) {
			return true;
		}
		//
		if (Debug.DEBUG) {
			Log.d(TAG, "no handler available to service this request");
		}
		return false;
	}
	
	protected void attachSession(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// check sid
		String sid = scan(request.getCookies(), SESSION_KEY);
		Session session = null;
		if (Debug.DEBUG) {
			Log.d(TAG, "attachSession sid: " + sid);
		}
		if (sid == null || ((session = sessions.get(sid)) == null)) {
			return;
		}
		request.setAttribute(SESSION_KEY, session);
		response.addCookie(new Cookie(SESSION_KEY, session.id));
	}
}
